package com.aracky.system.service.impl;

import com.aracky.common.util.ComUtil;
import com.aracky.common.vo.PageVO;
import com.aracky.system.mapper.SysPostMapper;
import com.aracky.system.model.entity.SysPost;
import com.aracky.system.model.entity.SysUserPost;
import com.aracky.system.model.request.PostDeptRequest;
import com.aracky.system.model.request.SysPostRequest;
import com.aracky.system.model.vo.PostDeptVO;
import com.aracky.system.model.vo.SysPostVO;
import com.aracky.system.service.SysPostService;
import com.aracky.system.service.SysUserPostService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 岗位信息表 服务实现类
 * </p>
 *
 * @author zzp
 * @since 2022-07-14 11:22:57
 */
@Service
public class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost> implements SysPostService {
    @Resource
    private SysPostMapper sysPostMapper;

    @Resource
    private SysUserPostService sysUserPostService;

    /**
     * 查询岗位列表
     *
     * @param sysPostRequest
     * @return
     */
    @Override
    public PageVO<SysPostVO> getPostPage(SysPostRequest sysPostRequest) {
        IPage<SysPostVO> page = sysPostMapper.findPost(sysPostRequest.toPage(), sysPostRequest);
        return PageVO.convertPage(page);
    }

    /**
     * 新增岗位
     *
     * @param sysPost
     * @return
     */
    @Override
    public int savePost(SysPost sysPost) {
        return sysPostMapper.insert(sysPost);
    }

    /**
     * 修改岗位信息
     *
     * @param sysPost
     * @return
     */
    @Override
    public int updatePost(SysPost sysPost) {
        return sysPostMapper.updateById(sysPost);
    }

    /**
     * 删除岗位信息
     *
     * @param postId
     * @return
     */
    @Override
    public int deletePost(Long postId) {
        return sysPostMapper.deleteById(postId);
    }

    /**
     * 查询岗位详情
     *
     * @param postId
     * @return
     */
    @Override
    public SysPost getPostInfo(Long postId) {
        return sysPostMapper.selectById(postId);
    }

    /**
     * 岗位绑定用户
     *
     * @param postId
     * @param userIds
     */
    @Override
    public void saveUserPost(Long postId, Long[] userIds) {
        LambdaQueryWrapper<SysUserPost> lambdaQueryWrapper
                = Wrappers.<SysUserPost>lambdaQuery().eq(SysUserPost::getPostId, postId);
        sysUserPostService.remove(lambdaQueryWrapper);

        if (userIds == null || userIds.length == 0) {
            return;
        }

        SysUserPost userPost;
        // 新增用户与角色管理
        List<SysUserPost> list = new ArrayList<SysUserPost>(userIds.length);
        for (Long userId : userIds) {
            userPost = new SysUserPost();
            userPost.setUserId(userId);
            userPost.setPostId(postId);
            list.add(userPost);
        }
        sysUserPostService.saveBatch(list);
    }


    /**
     * 思路：存入进来的数据是存在：部门id，岗位名称，微信用户id,
     * 即部门-岗位与用户一对多，但是我们保存岗位，可能只需要保存一个
     * 保存之前，先对已存在的设置岗位id，不存在的需要进行新增
     * 新增需要按照岗位名称和部门id进行筛选
     * 新增成功之后需要对原来存在微信用户id的数据进行岗位id赋值
     * 返回的数据用于构建岗位和员工的关系
     *
     * @param sysPostList
     * @return
     */
    @Override
    public List<SysPost> saveWxPost(List<SysPost> sysPostList) {
        if (ComUtil.isNullList(sysPostList)) {
            return null;
        }

        //查询数据库的岗位
        List<SysPost> dbPostList = this.list();
        //通过部门和名称查询，如果存在就设置部门id
        Map<String, Long> dbWxPostMap = dbPostList.stream()
                .collect(Collectors.toMap(post -> post.getDeptId() + post.getPostName(), SysPost::getPostId,(value1,value2)->value2));

        //不需要保存的数据
        List<SysPost> noSavePostList = new ArrayList<>(sysPostList.size());

        //需要保存的数据
        List<SysPost> savePostList = new ArrayList<>(sysPostList.size());

        for (SysPost post:sysPostList) {
            boolean pass = dbWxPostMap.containsKey(post.getDeptId() + post.getPostName());
            if (pass) {
                post.setPostId(dbWxPostMap.get(post.getDeptId() + post.getPostName()));
                noSavePostList.add(post);
                continue;
            }
            savePostList.add(post);
        }


        //需要对保存数据进行刷选，因为部门下存在多人，不能让部门保存多个数据
        List<SysPost> saveDbPostList = savePostList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(post -> post.getDeptId() + ":" + post.getPostName()))),
                        ArrayList::new));

        this.saveBatch(saveDbPostList);

        //这里根据部门id和岗位名称进行组合，为了给之前的数据赋值岗位id
        Map<String, Long> savePostMap = saveDbPostList.stream()
                .collect(Collectors.toMap(post -> post.getDeptId() + post.getPostName(), SysPost::getPostId));

        savePostList.stream().forEach(post -> {
            post.setPostId(savePostMap.get(post.getDeptId() + post.getPostName()));
        });

        //返回数据结果
        savePostList.addAll(noSavePostList);

        return savePostList;
    }

    /**
     * 根据条件分页查询岗位部门
     *
     * @param postDeptRequest
     * @return
     */
    @Override
    public PageVO<PostDeptVO> getPostDept(PostDeptRequest postDeptRequest) {
        if (null == postDeptRequest) {
            return null;
        }
        IPage<PostDeptVO> iPage = sysPostMapper.selectPostDept(postDeptRequest.toPage(),postDeptRequest);
        return PageVO.convertPage(iPage);
    }
}
